import { createRouter, createWebHashHistory } from 'vue-router'
import { staticRoutes, initSystemData } from './hook'
import { Ui, cache, hasRoute, NextLoading } from '@/utils'
import { useRouterStore } from '@/store'

const router = createRouter({
  history: createWebHashHistory(),
  routes: staticRoutes
})

router.beforeEach(async (to, from, next) => {
  const token = cache.getToken()
  const routerStore = useRouterStore()

  if (!token && to.path !== '/login') {
    next('/login')
  } else {
    if (!routerStore.routerList.length && token) {
      const res: any = await initSystemData()
      if (res.code !== 0) {
        next('/login')
      } else {
        // next({ path: to.path, query: to.query })
        next({ path: to.path })
      }
    } else {
      if (hasRoute(to.path)) {
        next()
      } else {
        Ui.useNotice(`您没有对应的菜单权限,请联系管理员`)
        next({ path: from.path })
      }
    }
  }
})

router.afterEach(() => {
  if (window.nextLoading) NextLoading.done(300)
})

export default router
